<template>
  <div class="dashboard-wrapper">
    <div class="dashboard-container">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>柜子总数</span>
            </div>
            <div class="card-content">
              <h2>{{ totalCabinets }}</h2>
              <p>个柜子</p>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>使用中</span>
            </div>
            <div class="card-content">
              <h2>{{ inUseCabinets }}</h2>
              <p>个柜子</p>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>空闲</span>
            </div>
            <div class="card-content">
              <h2>{{ availableCabinets }}</h2>
              <p>个柜子</p>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="mt-20">
        <!-- ECharts Chart Container: Cabinet Status Overview -->
        <el-col :span="12">
          <el-card>
            <div ref="cabinetChart" style="width: 100%; height: 300px;"></div>
          </el-card>
        </el-col>

        <!-- ECharts Usage Trend Chart Container: Area Usage -->
        <el-col :span="12">
          <el-card>
            <div ref="usageTrendChart" style="width: 100%; height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="mt-20">
        <el-col :span="24">
          <el-card>
            <div slot="header" class="clearfix">
              <span>最近使用记录</span>
            </div>
            <el-table :data="userRecords" style="width: 100%">
              <el-table-column prop="cabinetId" label="柜子编号" width="120" />
              <el-table-column prop="username" label="使用者" width="120" />
              <el-table-column prop="startTime" label="开始时间" width="180" />
              <el-table-column prop="endTime" label="结束时间" width="180" />
              <el-table-column prop="status" label="状态">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.status === '使用中' ? 'success' : 'info'">
                    {{ scope.row.status }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>

      <!-- Current user occupied cabinets -->
      <el-row :gutter="20" class="mt-20" v-if="occupiedCabinets.length > 0">
        <el-col :span="24">
          <el-card>
            <div slot="header" class="clearfix">
              <span>我当前占用的柜子</span>
            </div>
            <el-table :data="occupiedCabinets" style="width: 100%">
              <el-table-column prop="id" label="柜子编号" width="120" />
              <el-table-column prop="startTime" label="开始时间" width="180">
                <template slot-scope="scope">
                  {{ formatDate(scope.row.startTime) }}
                </template>
              </el-table-column>
              <el-table-column label="占用时长" width="120">
                <template slot-scope="scope">
                  {{ calculateDuration(scope.row.startTime, null) }} <!-- Occupied, end time is null -->
                </template>
              </el-table-column>
              <el-table-column prop="password" label="取件密码" width="120" />
              <el-table-column label="操作">
                <template slot="scope">
                  <el-button size="mini" type="danger" @click="handleReleaseCabinet(scope.row)">释放</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 取件密码对话框 -->
    <el-dialog
      title="请输入取件密码"
      :visible.sync="passwordDialogVisible"
      width="30%"
      @close="resetPasswordDialog"
    >
      <el-form :model="passwordForm" ref="passwordForm" @submit.native.prevent="handlePasswordSubmit">
        <el-form-item label="密码" prop="password" :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]" >
          <el-input type="password" v-model="passwordForm.password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="passwordDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handlePasswordSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapGetters } from "vuex";

export default {
  name: "Dashboard",
  data() {
    return {
      // 密码对话框的显示状态
      passwordDialogVisible: false,
      // 当前选中的要释放的柜子
      selectedCabinetForRelease: null,
      // 密码表单数据
      passwordForm: {
        password: ''
      },
      // ECharts图表实例
      chartInstance: null,
      // 使用趋势图表实例
      usageTrendChartInstance: null,
      // 区域使用数据
      areaUsageData: { areas: [], counts: [] }
    };
  },
  computed: {
    // 从Vuex获取状态
    ...mapState({
      user: (state) => state.user,
      allCabinets: (state) => state.cabinets.cabinets
    }),
    ...mapGetters(['userRecords']),
    // 计算当前用户占用的柜子
    occupiedCabinets() {
      if (!this.user || !this.allCabinets) return [];
      return Object.values(this.allCabinets).filter(
        (cabinet) => cabinet.status === "in_use" && cabinet.userId === (this.user ? this.user.id : null)
      );
    },
    // 计算柜子总数
    totalCabinets() {
        return Object.keys(this.allCabinets).length;
    },
    // 计算使用中的柜子数量
    inUseCabinets() {
        return Object.values(this.allCabinets).filter(cabinet => cabinet.status === 'in_use').length;
    },
    // 计算空闲的柜子数量
    availableCabinets() {
        return Object.values(this.allCabinets).filter(cabinet => cabinet.status === 'available').length;
    }
  },
  methods: {
    // 格式化日期显示
    formatDate(date) {
      if (!date) return "-";
      return new Date(date).toLocaleString();
    },
    // 计算使用时长
    calculateDuration(startTime) {
      if (!startTime) return "-";
      const start = new Date(startTime);
      const now = new Date();
      const diff = now - start;
      const hours = Math.floor(diff / (1000 * 60 * 60));
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
      const seconds = Math.floor((diff % (1000 * 60)) / 1000);
      return `${hours}小时${minutes}分钟${seconds}秒`;
    },
    // 处理释放柜子操作
    handleReleaseCabinet(cabinet) {
       this.selectedCabinetForRelease = cabinet;
       this.passwordDialogVisible = true;
    },
    // 处理密码提交
    handlePasswordSubmit() {
        this.$refs.passwordForm.validate(async (valid) => {
            if(valid) {
                if(this.passwordForm.password === this.selectedCabinetForRelease.password) {
                    try {
                        // 调用释放柜子的action
                        await this.$store.dispatch('releaseCabinet', { cabinetId: this.selectedCabinetForRelease.id, password: this.passwordForm.password });
                        this.$message.success('柜子已释放');
                        this.passwordDialogVisible = false;
                        this.resetPasswordDialog();
                        // 更新图表显示
                        this.updateChart();
                        this.calculateAreaUsage();
                    } catch (error) {
                        this.$message.error(error.message || '释放失败');
                    }
                } else {
                    this.$message.error('密码不正确');
                }
            } else {
                console.log('error submit!!');
                return false;
            }
        });
    },
    // 重置密码对话框
    resetPasswordDialog() {
        this.passwordForm.password = '';
        this.$nextTick(() => {
           if (this.$refs.passwordForm) {
             this.$refs.passwordForm.resetFields();
           }
        });
        this.selectedCabinetForRelease = null;
    },
    // 初始化状态概览图表
    initChart() {
        this.$nextTick(() => {
             if (window.echarts && this.$refs.cabinetChart) {
                this.chartInstance = window.echarts.init(this.$refs.cabinetChart);
                this.updateChart();
            } else {
                console.error('ECharts或图表容器不可用');
            }
        });
    },
    // 更新状态概览图表
    updateChart() {
        if (!this.chartInstance) {
             console.error('状态图表实例未初始化');
            return;
        }

        // 配置图表选项
        const option = {
            title: {
                text: '柜子状态概览',
                left: 'center'
            },
            tooltip: {
                 trigger: 'axis',
                 axisPointer: {
                     type: 'shadow'
                 }
            },
            legend: {
                data: ['数量'],
                right: '10%'
            },
            xAxis: {
                data: ["总数", "使用中", "空闲"],
                 axisTick: {
                    alignWithLabel: true
                }
            },
            yAxis: {
                type: 'value',
                minInterval: 1
            },
            grid: {
                top: 60,
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            series: [{
                name: '数量',
                type: 'bar',
                data: [this.totalCabinets, this.inUseCabinets, this.availableCabinets],
                 itemStyle: {
                     color: '#409EFF'
                 }
            }]
        };

        this.chartInstance.setOption(option);
    },
    // 初始化区域使用图表
    initAreaUsageChart() {
        this.$nextTick(() => {
             if (window.echarts && this.$refs.usageTrendChart) {
                this.usageTrendChartInstance = window.echarts.init(this.$refs.usageTrendChart);
                this.calculateAreaUsage();
            } else {
                console.error('ECharts或使用趋势图表容器不可用');
            }
        });
    },
    // 计算区域使用情况
    calculateAreaUsage() {
        console.log('计算区域使用情况...');
        const usageCounts = {};
        const allRecords = this.$store.getters.getCabinetRecords;
        const allCabinets = this.$store.getters.getAllCabinets;
        const cabinetAreaMap = {};

        // 创建柜子ID到区域的映射
        allCabinets.forEach(cabinet => {
            cabinetAreaMap[cabinet.id] = cabinet.area;
        });

        // 统计每个区域的使用次数
        allRecords.forEach(record => {
            if (record.status === 'completed' && cabinetAreaMap[record.cabinetId]) {
                const area = cabinetAreaMap[record.cabinetId];
                usageCounts[area] = (usageCounts[area] || 0) + 1;
            }
        });

        // 更新区域使用数据
        this.areaUsageData.areas = Object.keys(usageCounts);
        this.areaUsageData.counts = Object.values(usageCounts);

        console.log('区域使用数据:', this.areaUsageData);

        this.updateAreaUsageChart();
    },
    // 更新区域使用图表
    updateAreaUsageChart() {
        if (this.usageTrendChartInstance) {
            const option = {
                title: {
                    text: '各区域柜子使用次数统计',
                    left: 'center'
                },
                tooltip: {},
                xAxis: {
                    type: 'category',
                    data: this.areaUsageData.areas
                },
                yAxis: {
                    type: 'value'
                },
                grid: {
                    top: 60,
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                series: [{
                    name: '使用次数',
                    type: 'bar',
                    data: this.areaUsageData.counts
                }]
            };
            this.usageTrendChartInstance.setOption(option);
        }
    }
  },
  // 监听数据变化
  watch: {
      allCabinets: {
          handler() {
              this.updateChart();
          },
          deep: true
       },
       userRecords: {
           handler() {
               this.calculateAreaUsage();
           },
           deep: true
        }
    },
  // 组件挂载时初始化
  mounted() {
    // 初始化图表
    this.initChart();
    this.initAreaUsageChart();

    // 设置定时器更新使用时长
    this.timer = setInterval(() => {
        this.$forceUpdate();
    }, 1000);

    // 添加窗口大小变化监听
    window.addEventListener('resize', this.handleResize);
  },
  // 组件销毁前清理
  beforeDestroy() {
    // 清除定时器
    if (this.timer) {
        clearInterval(this.timer);
    }
    // 销毁图表实例
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
    if (this.usageTrendChartInstance) {
       this.usageTrendChartInstance.dispose();
     }
    // 移除窗口大小变化监听
    window.removeEventListener('resize', this.handleResize);
  },
};
</script>

<style scoped>
.dashboard-wrapper {
  height: 100%;
}

.dashboard-container {
  padding: 20px;
}

.mt-20 {
  margin-top: 20px;
}

.box-card {
  text-align: center;
}

.card-content {
  padding: 20px 0;
}

.card-content h2 {
  font-size: 36px;
  margin: 0;
  color: #409eff;
}

.card-content p {
  margin: 10px 0 0;
  color: #909399;
}
</style>
